package com.inkegz.message.repo.action

import android.util.Log
import com.inkegz.message.entity.MessageEntity
import com.inkegz.message.entity.MessageEntity_
import com.inkegz.message.repo.base.ObjectBoxAction
import com.inkegz.message.repo.base.ObjectBoxState
import com.inkegz.message.utils.conversationBox
import com.inkegz.message.utils.messageBox
import com.inkegz.message.utils.queryConversation
import io.objectbox.kotlin.inValues

/**
 * 添加 消息 操作
 */
class AddMessageAction(
    private val conversationKey: String,
    private val messageList: List<MessageEntity>
) : ObjectBoxAction() {

    override suspend fun opt(state: ObjectBoxState): ObjectBoxState {
        val conversation = state.queryConversation(conversationKey)
            ?: run {
                Log.e("ImRepo", "can not find conversation when add message")
                return state
            }
        Log.i("ImRepo","addMessageAction conversationKey: $conversationKey messageIdList: ${messageList.map { message -> message.messageId }}")
        val messageBox = state.messageBox()
        val messages = conversation.messages
        val localMessageMap = messageBox.query()
            .inValues(MessageEntity_.messageId, messageList.map(MessageEntity::messageId).toLongArray())
            .build()
            .find()
            .associate { localMessage -> localMessage.messageId to localMessage.id }
        val messageMap = messages.associateBy { message -> message.messageId }
        messageList.forEach { message ->
            val localId = localMessageMap[message.messageId]
            localId?.also { id ->
                message.id = id
                messageBox.put(message)
            }
            messageMap[message.messageId]?.also{ msg -> messages.remove(msg) }
        }
        messages.addAll(messageList)
        state.conversationBox().put(conversation)
        return ObjectBoxState(state.model)
    }
}